package pl.grumpy.tvforecast;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class SeriesDetails extends Activity {
	private TVSerie tvSerie = null;
	private Bitmap bmImg;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.series_details);

		final TextView tvST = (TextView) findViewById(R.id.tvSeriesTitle);
		final TextView tvSD = (TextView) findViewById(R.id.tvSeriesDesc);

		Intent intent = getIntent();
		tvSerie = (TVSerie) intent.getSerializableExtra("tvSerie");

		if (tvSerie.getTitle() != null)
			tvST.setText(tvSerie.getTitle());
		tvSD.setText(tvSerie.getDescription());

		if (tvSerie.getBanner() != null) {
			Log.v("AAAAAA", "" + tvSerie.getBanner().toString());
			threadedGetSeriesImage();
		}
		// TODO: pobrac seriesid :)
		// TODO: pobrac adres obrazka !
	}

	private void threadedGetSeriesImage() {
		// TODO: pobrac adres obrazka zeby cos pobierac
		final ImageView ivSI = (ImageView) findViewById(R.id.ivSeriesImage);

		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				tvSerie.setBannerImg(bmImg);
				ivSI.setImageBitmap(bmImg);
				// putTitlesIntoListView(lvSearchResults);
			}
		};

		Runnable getImage = new Runnable() {
			public void run() {
				try {
					try {
						HttpURLConnection conn = (HttpURLConnection) tvSerie
								.getBanner().openConnection();
						conn.setDoInput(true);
						conn.connect();
						InputStream is = conn.getInputStream();

						bmImg = BitmapFactory.decodeStream(is);

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					handler.sendEmptyMessage(RESULT_OK);
				} catch (Exception e) {
					Log.e("TV Forecast", e.getLocalizedMessage());
				}
			}
		};

		Thread getImageTask = new Thread(getImage);
		getImageTask.start();
	}
	// koniec klasy

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		ImageView ivST = (ImageView)findViewById(R.id.ivSeriesImage);
		tvSerie = (TVSerie) savedInstanceState.getSerializable("tvSerie");
		if (tvSerie.getBannerImg() != null)
			ivST.setImageBitmap(tvSerie.getBannerImg());
		
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putSerializable("tvSerie", tvSerie);
		super.onSaveInstanceState(outState);
	}
}
